<template>
  <div>
    <DeptTab />
    <div v-loading="loading" :class="{'mobile-table':showMobilePage}" class="dept-container">
      <div class="dept-header">
        <div class="header-crumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item
              :class="crumbList.length && 'crumb-active'"
              @click.native="onCrumbChange(-1)"
            >飞博共创</el-breadcrumb-item>
            <el-breadcrumb-item
              v-for="(crumb, index) in crumbList"
              :key="crumb.id"
              :class="index !== crumbList.length - 1 && 'crumb-active'"
              @click.native="onCrumbChange(index)"
            >{{ crumb.departmentName }}</el-breadcrumb-item>
          </el-breadcrumb>
          <div v-if="showMobilePage" class="mobile-tip">(☝支持左右滑动)</div>
        </div>
        <el-button v-if="hasRouteAuth('auth:department:create')" type="primary" size="small" class="ok" @click="deptAddDialogShow">添加部门</el-button>
      </div>
      <div class="page-container">
        <div v-if="curDeptList.length">
          <template v-for="item in curDeptList">
            <div
              :key="item.id"
              :style="{cursor: setRowCursorType(item)}"
              class="box"
              @click="getChildList(item)"
            >
              <div class="box-content">
                <template v-if="item.isDepartment === 1">
                  <img :src="organizationImg" class="dept-tag" alt="">
                  <div>{{ item.departmentName }}<span style="white-space: nowrap">({{ item.peopleNum }}人)</span></div>
                </template>
                <template v-else>
                  <img :src="item.avatar || avatarImg" alt="头像" class="avatar">
                  <div class="user-info">
                    <div class="flex-center">
                      <span>{{ item.userName }}</span>
                      <el-tag v-if="item.isLeader" class="user-tag" size="mini">主管</el-tag>
                      <el-tag v-if="item.isCustomLeader" class="user-tag" size="mini">主管(共创)</el-tag>
                    </div>
                    <span class="post">{{ item.post }}</span>
                  </div>
                </template>
                <span v-if="item.isBusinessEntiy" class="business-entiy">经营体</span>
              </div>
              <div v-if="hasRouteAuth('auth:department:setLeader') && !item.isDepartment && (!item.isLeader || (item.isLeader && item.isCustomLeader))" class="operation-btn-group">
                <el-button type="text" @click="setCustomLeader(item)">{{ item.isCustomLeader ? '取消主管' : '设为主管' }}</el-button>
              </div>
              <div v-if="item.children" class="operation-btn-group">
                <template v-if="!showMobilePage">
                  <el-button v-if="showActionBtn(item.isCustom, 'edit')" type="text" @click.stop="deptEditDialogShow(item)">编辑</el-button>
                  <div v-if="showActionBtn(item.isCustom, 'delete')" class="btn-divider" />
                  <el-button v-if="showActionBtn(item.isCustom, 'delete')" class="del-btn" type="text" @click.stop="handleDeptDel(item.departmentId)">删除</el-button>
                  <el-icon :style="item.children.length ? 'opacity: 1' : 'opacity: 0'" class="el-icon-arrow-right"/>
                </template>
                <tableOperateBtn v-else>
                  <el-dropdown-item v-if="showActionBtn(item.isCustom, 'edit')" style="width:90px;text-align: center" @click.native="deptEditDialogShow(item)">
                    <div>编辑</div>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="showActionBtn(item.isCustom, 'delete')" style="width:90px;text-align: center" @click.native="handleDeptDel(item.departmentId)">
                    <div>删除</div>
                  </el-dropdown-item>
                </tableOperateBtn>
              </div>
            </div>
          </template>
        </div>
        <div v-else-if="!isInit" class="empty-container">
          <img :src="emptyImg" alt="">
          <div class="empty-text">暂无数据</div>
        </div>
        <DeptDialog
          ref="deptDialog"
          v-model="deptValues"
          :dept-tree-list="deptTreeList"
          :is-edit="isEdit"
          :loading="loading"
          @handleDeptEdit="handleDeptEdit"
          @handleDeptCreate="handleDeptCreate"
          @handleCancel="handleCancel"
        />
      </div>
    </div>
  </div>
</template>

<script>
import DeptTab from './components/deptTab';
import DeptDialog from './modal/deptDialog';
import tableOperateBtn from '@/components/Common/tableOperateBtn';
import avatarImg from '@/assets/user-avatar.png';
import organizationImg from '@/assets/setting/organization.png';
import { allDeptlist } from '@/api/select';
import { getDepartmentAll } from '@/api/config';
import { isEmpty } from '@/utils/array';
import { showModal } from '@/utils/message';
import { customDepartmentDelete, customDepartmentCreate, customDepartmentEdit, setUserLeader } from '@/api/department';
import { hasRouteAuth } from '@/utils/permission';
import emptyImg from '@/assets/empty-table-data.png';
import mobileTable from '@/mixins/mobileTable';

export default {
  name: 'DepartmentManage',
  components: {
    DeptTab,
    DeptDialog,
    tableOperateBtn
  },
  mixins: [mobileTable],
  data() {
    return {
      avatarImg,
      emptyImg,
      organizationImg,
      crumbList: [],
      allDeptList: [],
      curDeptList: [],
      deptValues: {
        deptName: '',
        parentId: '',
        isBusinessEntiy: 0,
        isCustom: ''
      },
      deptTreeList: [],
      isEdit: false,
      loading: false,
      isInit: true
    };
  },
  created() {
    this.queryList();
    this.queryDeptTreeList();
  },
  methods: {
    hasRouteAuth,
    showActionBtn(val, type) {
      return type === 'edit' ? this.hasRouteAuth('auth:department:create') : this.hasRouteAuth('auth:department:create') && !!val;
    },
    setRowCursorType(data) {
      return isEmpty(data.children) ? 'default' : 'pointer';
    },
    resetDeptValues() {
      this.deptValues = { deptName: '', parentId: '', isBusinessEntiy: '', isCustom: '' };
    },
    resetData() {
      this.resetDeptValues();
      this.queryList(false);
      this.queryDeptTreeList();
    },
    async queryList(resetList = true) {
      try {
        this.loading = true;
        const result = await allDeptlist();
        this.allDeptList = result && result.data || [];
        if (!this.crumbList.length || resetList) {
          this.curDeptList = this.allDeptList;
        } else {
          this.resetCrumbList();
        }
        this.loading = false;
        this.isInit = false;
      } catch (e) {
        this.loading = false;
      }
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        const deptTreeList = [{
          dingdingDeptId: 1,
          name: '飞博共创'
        }];
        deptTreeList[0].children = (res && res.data) || [];
        this.deptTreeList = deptTreeList;
      });
    },
    getChildList(data) {
      if (isEmpty(data.children)) return;
      this.crumbList.push(data);
      this.curDeptList = data.children;
    },
    handleCancel() {
      this.resetDeptValues();
    },
    deptAddDialogShow() {
      this.isEdit = false;
      this.$refs['deptDialog'].dialogVisible = true;
    },
    deptEditDialogShow(deptData = {}) {
      const { departmentName, departmentId, parentId, isBusinessEntiy, isCustom } = deptData;
      this.deptValues.deptName = departmentName;
      this.deptValues.id = departmentId;
      this.deptValues.parentId = parentId;
      this.deptValues.isBusinessEntiy = isBusinessEntiy;
      this.deptValues.isCustom = isCustom;
      this.isEdit = true;
      this.$refs['deptDialog'].dialogVisible = true;
    },
    // 删除
    handleDeptDel(id) {
      if (!id) {
        this.$message.error('无法获取部门id');
        return;
      }
      showModal('请确定是否删除该部门').then(() => {
        this.loading = true;
        customDepartmentDelete({ id }).then(_ => {
          this.loading = false;
          this.$message.success('删除成功');
          this.resetData();
        }).catch(_ => {
          this.loading = false;
        });
      });
    },
    // 编辑
    handleDeptEdit() {
      this.loading = true;
      customDepartmentCreate(this.deptValues).then(_ => {
        this.$refs['deptDialog'].handleDialogClose();
        this.loading = false;
        this.$message.success('保存成功');
        this.resetData();
      }).catch(_ => {
        this.loading = false;
      });
    },
    // 添加
    handleDeptCreate() {
      this.loading = true;
      customDepartmentEdit(this.deptValues).then(_ => {
        this.$refs['deptDialog'].handleDialogClose();
        this.loading = false;
        this.$message.success('部门添加成功');
        this.resetData();
      }).catch(_ => {
        this.loading = false;
      });
    },
    onCrumbChange(index) {
      if (index === -1) {
        this.crumbList = [];
        this.curDeptList = this.allDeptList;
        return;
      }
      this.crumbList.splice(index + 1);
      this.curDeptList = this.crumbList.slice(-1)[0].children;
    },
    // 更新面包屑的当前列表的数据
    resetCrumbList() {
      const crumbArray = [];
      let matchData = JSON.parse(JSON.stringify(this.allDeptList));
      this.crumbList.forEach(item => {
        const curData = matchData.filter(_item => _item.id === item.id)[0];
        crumbArray.push(curData);
        matchData = curData.children;
      });
      this.crumbList = crumbArray;
      this.curDeptList = crumbArray.slice(-1)[0].children || [];
    },
    setCustomLeader(item) {
      const msg = item.isCustomLeader ? '取消主管' : '设为主管';
      showModal(`请确定是否${msg}`).then(() => {
        const departmentId = item.id.split('_')[0];
        const params = {
          id: item.userId,
          isCustomLeader: item.isCustomLeader ? 0 : 1,
          departmentId: Number(departmentId)
        };
        this.loading = true;
        setUserLeader(params).then(_ => {
          this.loading = false;
          this.$message.success('操作成功');
          this.resetData();
        }).catch(_ => {
          this.loading = false;
        });
      });
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-loading-mask {
  z-index: 2050;
}
.flex-center {
  display: flex;
  align-items: center;
}
.dept-container {
  margin: 16px;
  background-color: #fff;
  padding: 20px;
  min-height: calc(100vh - 32px - 48px);
  .dept-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .header-crumb {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin-right: 20px;
      ::v-deep .el-breadcrumb__inner {
        font-size: 14px;
        color: #999;
      }
      .crumb-active {
        ::v-deep .el-breadcrumb__inner {
          color: #333;
          cursor: pointer;
        }
      }
    }
  }
  .page-container {
    background-color: #fff;
    .box {
      height: 60px;
      padding-left: 8px;
      padding-right: 15px;
      display: flex;
      align-items: center;
      font-weight: bold;
      font-size: 14px;
      justify-content: space-between;
      .box-content {
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 14px;
        > img {
          margin-right: 12px;
          background-color: #EFF3FB;
          width: 34px;
          height: 34px;
        }
        .dept-tag {
          border-radius: 4px;
          width: 32px;
          height: 32px;
          padding: 7px;
        }
        .avatar {
          border-radius: 50%;
        }
        .user-info {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .user-tag {
            border: none;
            border-radius: 999px;
            padding: 0 8px;
            margin-left: 5px;
          }
          .post {
            color: #999;
            font-weight: normal;
            font-size: 12px;
            margin-top: 2spx;
          }
        }
      }
      .operation-btn-group {
        display: flex;
        align-items: center;
        white-space: nowrap;
        margin-left: 16px;
        .btn-divider {
          height: 12px;
          width: 1px;
          background-color: #ddd;
          margin: 0 8px;
        }
        .del-btn {
          // margin-right: 40px;
          color: red;
        }
        .el-button {
          font-size: 14px;
        }
      }
    }
    .empty-container {
      margin: 50px auto;
      img {
        width: 120px;
        margin: 0 auto;
        display: block;
      }
      .empty-text {
        color: #666;
        font-size: 15px;
        text-align: center;
      }
    }
    .box:hover {
      background-color: #F5F5F5;
    }
  }
}
.business-entiy {
  margin-left: 10px;
  border: 1px solid #fd8546;
  border-radius: 4px;
  padding: 2px 6px;
  color: #fd8546;
  font-size: 12px;
  line-height: 16px;
}
.mobile-table {
  .dept-header {
    position: relative;
    padding: 0 12px;
    ::v-deep {
      .el-breadcrumb {
        max-width: calc(100vw - 150px);
        overflow-x: auto;
        white-space: nowrap;
        .el-breadcrumb__item {
          float: none;
        }
      }
    }
  }
  .mobile-tip {
    position: absolute;
    top: 22px;
    left: 12;
    font-size: 12px;
    color: #999;
  }
}
</style>
